package com.charles.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.charles.core.AppIdClient;
import com.charles.entity.ShortUrl;
import com.charles.mapper.ShortUrlMapper;
import com.charles.service.ShortUrlService;
import com.charles.utils.ConvertUtils;
import com.charles.vo.param.ShortUrlParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;

/**
 * @author charles
 * @date 2022/9/4 13:57
 */
@Service
@Slf4j
public class ShortUrlServiceImpl implements ShortUrlService {

    @Value("${short.url.prefix}")
    private String shortUrlPrefix;

    @Autowired
    private ShortUrlMapper shortUrlMapper;

    @Override
    public String shorten(ShortUrlParam shortUrlParam) {
        String originUrl = shortUrlParam.getOriginUrl();
        String urlMd5 = SecureUtil.md5(originUrl);
        List<ShortUrl> urls = shortUrlMapper.selectList(new QueryWrapper<ShortUrl>().lambda().eq(ShortUrl::getUrlMd5, urlMd5).eq(ShortUrl::getAppCode, shortUrlParam.getAppCode()));
        if (urls.size() > 0) {
            return urls.get(0).getShortUrl();
        }
        if (Objects.isNull(shortUrlParam.getCodeLen())) {
            shortUrlParam.setCodeLen(6);
        }
        Long sequence = AppIdClient.nextId(shortUrlParam.getBizType());
        log.info("seq: {}", sequence);
        String compressCode = StrUtil.padPre(ConvertUtils.hex10To62(sequence), shortUrlParam.getCodeLen(), "0");
        String shortUrl = shortUrlPrefix + compressCode;
        ShortUrl entity = ShortUrl.builder().shortUrl(shortUrl).compressCode(compressCode).originUrl(originUrl).bizType(shortUrlParam.getBizType()).createDate(LocalDateTime.now()).urlMd5(urlMd5).appCode(shortUrlParam.getAppCode()).build();
        shortUrlMapper.insert(entity);
        return shortUrl;
    }

    @Override
    public ShortUrl getOriginUrl(String compressCode) {
        List<ShortUrl> shortUrls = shortUrlMapper.selectList(new QueryWrapper<ShortUrl>().eq("compress_code", compressCode));
        if (shortUrls.size() > 0) {
            return shortUrls.get(0);
        }
        return null;
    }

    @Override
    public void save(ShortUrl shortUrl) {
        shortUrlMapper.insert(shortUrl);
    }
}
